<template>
  <div>
    <!-- 表单区域 -->
    <el-card>
      <el-form :inline="true">
        <el-form-item>
          <el-input placeholder="请输入搜索内容" v-model="query" clearable @clear="getUsers()">
            <!-- 搜索按钮 -->
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchUser"
            ></el-button>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addUser">添加用户</el-button>
        </el-form-item>
      </el-form>
      <!-- 用户列表区域 -->
      <el-table :data="userList" border style="width: 100%">
        <el-table-column label="#" width="80">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="username" label="姓名" width="140"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态" width="80">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ccc"
              @change="changeState(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="edit(scope.row)"></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="remove(scope.row.id)"
            ></el-button>
            <el-button type="warning" icon="el-icon-star-off" size="mini"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pages">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagenum"
          :page-sizes="[2, 4, 6, 8]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totals"
        >
        </el-pagination>
      </div>
    </el-card>
    <!-- 添加用户的模态框 -->
    <el-dialog title="添加用户" :visible.sync="addForm" @closed="resetAddForm">
      <el-form :model="addformData" ref="addform" :rules="rules">
        <el-form-item label="用户名" :label-width="'80px'" prop="username">
          <el-input v-model="addformData.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="'80px'" prop="password">
          <el-input v-model="addformData.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="'80px'" prop="email">
          <el-input v-model="addformData.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="'80px'" prop="mobile">
          <el-input v-model="addformData.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addForm = false">取 消</el-button>
        <el-button type="primary" @click="doAddUser('addform')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改的模态框 -->
    <el-dialog title="编辑用户" :visible.sync="editForm" >
      <el-form :model="editFormData" ref="editform" :rules="rules">
        <el-form-item label="用户名" :label-width="'80px'" prop="username">
          <el-input v-model="editFormData.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="'80px'" prop="email">
          <el-input v-model="editFormData.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="'80px'" prop="mobile">
          <el-input v-model="editFormData.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editForm = false">取 消</el-button>
        <el-button type="primary" @click="doEdit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "",
  data() {
    //验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/;
      if (regEmail.test(value)) {
        return cb();
      }
      //返回一个错误提示
      cb(new Error("请输入合法的邮箱"));
    };
    //验证手机号码的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[34578]\d{9}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      //返回一个错误提示
      cb(new Error("请输入合法的手机号码"));
    };
    return {
      query: "",
      pagenum: 1,
      pagesize: 2,
      totals: 0,
      userList: [], //用户列表数据
      //添加用户的表单
      addForm: false, //默认不显示
      addformData: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名在3~10个字符之间",
            trigger: "blur"
          }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "用户名在6~15个字符之间",
            trigger: "blur"
          }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            validator: checkEmail,
            message: "邮箱格式不正确，请重新输入",
            trigger: "blur"
          }
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            validator: checkMobile,
            message: "手机号码不正确，请重新输入",
            trigger: "blur"
          }
        ]
      },
      // 修改的表单
      editForm: false,
      editFormData: {
        username: "",
        id: "",
        email: "",
        mobile: ""
      }
    };
  },
  created() {
    this.getUsers();
  },
  methods: {
    async getUsers() {
      // 请求用户列表接口数据
      let { data: res } = await this.$http.get(
        `users?query=${this.query}&pagenum=${this.pagenum}&pagesize=${
          this.pagesize
        }`
      );
      //   console.log(res);

      // 如果返回状态异常，则报错并返回
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户列表数据失败");
      }

      // 如果返回状态正常，则正常赋值
      this.userList = res.data.users;
      this.totals = res.data.total;
    },
    // 改变每页显示条数
    handleSizeChange(size) {
      this.pagesize = size;
      this.getUsers();
    },
    // 改变当前页
    handleCurrentChange(page) {
      this.pagenum = page;
      this.getUsers();
    },
    // 改变用户的状态
    async changeState(row) {
      // console.log(row);
      // 请求修改用户状态的接口数据
      let { data: res } = await this.$http.put(
        `users/${row.id}/state/${row.mg_state}`
      );
      // console.log(res);
      // 如果返回的状态异常，则提示报错并且把状态改为修改之前的状态
      if (res.meta.status !== 200) {
        row.mg_state = !row.mg_state;
        this.$message.error("用户状态修改失败");
      }
      // 否则提示状态修改成功
      this.$message.success("用户状态修改成功");
    },
    // 搜索功能
    searchUser() {
      // 重新调用接口数据即可
      this.getUsers();
    },
    // 点击添加用户按钮的相关操作
    addUser() {
      this.addForm = true;
    },
    // 关闭模态框的时候重置表单
    resetAddForm() {
      this.$refs.addform.resetFields();
    },
    // 点击确定按钮，添加用户的操作
    doAddUser(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          let { data: res } = await this.$http.post("users", this.addformData);
          // console.log(res);
          if (res.meta.status !== 201) {
            this.$message.error("添加用户信息失败");
          }
          this.$message.success(res.meta.msg);
          this.getUsers();
          this.addForm = false; ///关闭对话框
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 删除用户
    remove(id) {
      this.$confirm("您确定要删除该用户信息吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          let { data: res } = await this.$http.delete("users/" + id);
          // console.log(res);
          if (res.meta.status == 200) {
            this.$message.success(res.meta.msg);
            this.pagenum = 1; //返回第一页
            this.getUsers();
          } else {
            this.$message.error(res.meta.msg);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 修改第一步：回填表单
    edit(row) {
      this.editForm = true;
      this.editFormData.username = row.username;
      this.editFormData.email = row.email;
      this.editFormData.mobile = row.mobile;
      this.editFormData.id = row.id;
    },
    // 修改第二步：请求接口，修改数据
    async doEdit() {
      let { data: res } = await this.$http.put(
        "users/" + this.editFormData.id,
        this.editFormData
      );
      console.log(res);
      if (res.meta.status == 200) {
        this.$message.success(res.meta.msg);
        this.getUsers();
        this.editForm = false;
      } else {
        this.$message.error(res.meta.msg);
      }
    }
  },
  computed: {},
  watch: {}
};
</script>

<style scoped>
.pages {
  margin-top: 20px;
}
</style>
评论 ( 0 )